#include "downloadcontrol.h"
#include "downloadmanager.h"
#include "downloadserver.h"
#include "readdatathread.h"

#include <QCoreApplication>
#include <QThread>
#include <QDebug>
#include <QWaitCondition>
#include <QMutex>
#include <thread>

DownloadServer * DownloadServer::m_instance_ptr = nullptr;
QMutex m_mutex;

static DownloadManager *m_downloadManager = nullptr;
static DownloadControl *m_downloadControl = nullptr;

DownloadServer *DownloadServer::getInstance()
{
    if (m_instance_ptr == nullptr) {
        m_mutex.lock();
        if (m_instance_ptr==nullptr) {
            m_instance_ptr = new DownloadServer;
        }
        m_mutex.unlock();
    }
    return m_instance_ptr;
}

void DownloadServer::startDownload(std::string configFilePath)
{
    qDebug() << "DownloadServer::startDownload tid=" << QThread::currentThread();
    emit m_downloadControl->startDownload(configFilePath.c_str());
}

static std::thread *mainThread = nullptr;
static QMutex mutex;

bool DownloadServer::init()
{
    qDebug() << "DownloadServer::init() 1 " << QThread::currentThreadId();
    mutex.lock();

    if (mainThread==nullptr) {
        qDebug() << "DownloadServer::init() 2" << QThread::currentThreadId();
        mainThread = new std::thread([=](){
            qDebug() << "in DownloadServer(), create main thread tid=" <<QThread::currentThreadId();
            //获取QCoreApplication对象没有则创建一个
            QCoreApplication *qapp = QCoreApplication::instance();
            if (qapp == nullptr) {
                int argc = 0;
                char **argv = nullptr;
                qapp = new QCoreApplication(argc, argv);
            }
            //创建库所使用的事件循环对象
            QEventLoop eventloop;

            //QThread downloadThread;
            m_downloadManager = new DownloadManager;
            m_downloadControl = new DownloadControl;

            ReadDataThread *t = new ReadDataThread;
//            QObject::connect(t, &ReadDataThread::testSig, m_downloadManager, [=](int t){
//                qDebug() << "recieved t=" << t;
//            });

            QObject::connect(t, &ReadDataThread::testSig, m_downloadManager, &DownloadManager::receivedSig);
            t->start();
            //m_downloadControl->moveToThread(&downloadThread);

            QObject::connect(m_downloadControl, &DownloadControl::startDownload, m_downloadManager, &DownloadManager::startDownload);
            QObject::connect(m_downloadControl, &DownloadControl::stopDownload, m_downloadManager, &DownloadManager::stopDownload);

            //downloadThread.start();

            mutex.unlock();
            eventloop.exec();
        });
    } else {
        mutex.unlock();
        return true;
    }

    mutex.lock();
    mutex.unlock();
    return true;
}

DownloadServer::DownloadServer()
{


}
